package com.example.imgrecognition.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.imgrecognition.ImgCompareActivity;
import com.example.imgrecognition.ImgCompareFreActivity;
import com.example.imgrecognition.ImgRecognitionActivity;
import com.example.imgrecognition.MainActivity;
import com.example.imgrecognition.Model.Device;
import com.example.imgrecognition.Model.Updatefile;
import com.example.imgrecognition.MyApplication;
import com.example.imgrecognition.R;
import com.example.imgrecognition.TestNetActivity;
import com.example.imgrecognition.Util.ToastUtil;
import com.example.imgrecognition.service.State1Service;
import com.example.imgrecognition.service.StateService;
import com.google.gson.Gson;
import com.zk.code.net.FileUtil;
import com.zk.code.net.HttpUtil;
import com.zk.code.net.NetConfig;
import com.zk.code.net.NetUtil;
import com.zk.code.net.SerialNumber;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.crud.DataSupport;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * 拍照比对界面
 */
public class TakePhotoActivity extends AppCompatActivity implements SurfaceHolder.Callback,
        View.OnClickListener, Camera.PictureCallback ,NavigationView.OnNavigationItemSelectedListener{
    private SurfaceView mSurfaceView;
    private ImageView mIvStart;
    private TextView mTvCountDown;

    private SurfaceHolder mHolder;

    private Camera mCamera;

    private Handler mHandler = new Handler();

    private int mCurrentTimer = 1;

    private boolean mIsSurfaceCreated = false;
    private boolean mIsTimerRunning = false;

    private static int CAMERA_ID = 1; //前置摄像头
    private static final String TAG = TakePhotoActivity.class.getSimpleName();
    private static  ArrayList<String> arrList = new ArrayList<String>();//后置
    private static  ArrayList<String> arrLists = new ArrayList<String>();//前置
    private   ArrayList<String> arrList1;
    private   ArrayList<String> arrList2;
    public static TakePhotoActivity Instance;
    private Disposable mDisposable;
    private Timer timer;
    private Handler handlerJump;
    byte[] imgarr ;
//    private static String theendphoto = "";
//    private static String theprephoto = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo);
        Context context = this;
        ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
                .killBackgroundProcesses(context.getPackageName());
       /* try{
            Runtime.getRuntime().exec("su");
            Runtime.getRuntime().exec("reboot");
        }catch(Exception e){
            int i = 0;

        }*/

        /*PowerManager pm = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);
        pm.reboot(null);*/

        if(CAMERA_ID==1){
            CAMERA_ID = 0;
        }else{
            CAMERA_ID = 1;
        }

        if (TestNetActivity.isWiFiActive(TakePhotoActivity.this)) {
            getNewVersion();
        }
        startService();
        initView();
        initEvent();
        Instance = this;
        arrList1 = new ArrayList<String>();
        arrList2 = new ArrayList<String>();




        MyApplication.getInstance().addActivity(this);
        handlerJump = new Handler(){
            @Override
            public void handleMessage(Message msg) {

                if(msg!=null && msg.what == 1){
                        if(CAMERA_ID==0&&arrList.size()>1){
                            arrList1.add(arrList.get(0));
                            arrList1.add(arrList.get(1));
                            Intent intent = new Intent(TakePhotoActivity.this, ImgCompareActivity.class);
                            intent.putExtra("list",arrList1);
                            intent.putExtra("state",true);
                            intent.putExtra("imgarr",imgarr);
                            startActivity(intent);
                        }
                        if(CAMERA_ID==1&&arrLists.size()>1){
                            arrList2.add(arrLists.get(0));
                            arrList2.add(arrLists.get(1));
                            Intent intent = new Intent(TakePhotoActivity.this, ImgCompareFreActivity.class);
                            intent.putExtra("list",arrList2);
                            intent.putExtra("state",true);
                            intent.putExtra("imgarr",imgarr);
                            startActivity(intent);
                        }
                    }
                    super.handleMessage(msg);
            }
        };
        //SheduleTask();
        handler.postDelayed(runnable, 3000);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);
            }
        }

    }

    private void startService1() {
        Intent intent = new Intent();
        intent.setClass(TakePhotoActivity.this, State1Service.class);
        startService(intent);
    }

    int vcode ;
    private void getNewVersion() {

        try{
            RequestParams params = new RequestParams(NetConfig.HTTPHOST+"/version/check/getnewversion");
            HttpUtil.postData(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Gson gson = new Gson();
                    Updatefile updatefile = gson.fromJson(result, Updatefile.class);
                    Log.e("获得返回结果","结果"+updatefile.toString());
                    if(updatefile!=null){
                        vcode = updatefile.getVersioncode();

                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    int i = 0;
                }
                @Override
                public void onCancelled(CancelledException cex) {
                    int i = 0;
                }
                @Override
                public void onFinished() {
                    int i = 0;
                }
            });
        }catch(Exception ex){
            int i = 0;
        }

    }


    private void autoCheck() {
		// 设置定时器，每15秒自动切换
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Message m = new Message();
                m.what = 1;
                handlerJump.sendMessage(m);
            }
        };
        timer.schedule(task,15000,15000);
    }

    private void startService(){
        Intent intent = new Intent();
        intent.setClass(TakePhotoActivity.this, StateService.class);
        intent.putExtra("backcancamera",FileUtil.isCameraCanUse(0));
        intent.putExtra("frecancamera",FileUtil.isCameraCanUse(1));
        startService(intent);
    }

    @Override
    protected void onStart() {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }

        super.onStart();
    }

    @Override
    protected void onDestroy() {
        Log.e("acticity结束","拍照activity已经结束");
        handler.removeCallbacks(runnable);
        mHandler.removeCallbacks(timerRunnable);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        if(timer!=null){
           timer.cancel();
       }
        autoCheck();
        super.onResume();
    }


    private void clearInterval(){
        if(mDisposable!=null){
            mDisposable.dispose();
        }
    }


    @Override
    protected void onPause() {
//        ToastUtil.show(TakePhotoActivity.this,"onpause 执行中");
        if(timer!=null){
            timer.cancel();
        }
        stopPreview();
        //handler.removeCallbacks(runnable);
        //mHandler.removeCallbacks(timerRunnable);
        super.onPause();
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //要执行的事件
            if (!mIsTimerRunning) {
                mIsTimerRunning = true;
                mHandler.post(timerRunnable);
            }
            handler.postDelayed(this, 3000);
        }
    };

        private void initView() {
        mSurfaceView = (SurfaceView) findViewById(R.id.surface_view);
        mTvCountDown = (TextView) findViewById(R.id.count_down);
    }

    private void initEvent() {
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mIsSurfaceCreated = true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        try {
            if(!FileUtil.isAllCameraCanUse()){

            }else{
                startPreview();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mIsSurfaceCreated = false;
    }

    private void startPreview() {
        if (mCamera != null || !mIsSurfaceCreated) {
            Log.d(TAG, "startPreview will return");
            return;
        }

        if(FileUtil.isCameraCanUse(CAMERA_ID)){
            try {
                mCamera = Camera.open(CAMERA_ID);
            }catch(Exception e){
                e.printStackTrace();
            }
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setJpegQuality(10);
            int width = getResources().getDisplayMetrics().widthPixels;
            int height = getResources().getDisplayMetrics().heightPixels;
            Camera.Size size = getBestPreviewSize(width, height, parameters);
            if (size != null) {
                //设置预览分辨率
                parameters.setPreviewSize(size.width, size.height);
                //设置保存图片的大小
                // parameters.setPictureSize(size.width, size.height);
            }
            //自动对焦
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            parameters.setPreviewFrameRate(20);
            //设置相机预览方向
            mCamera.setDisplayOrientation(90);
            mCamera.setParameters(parameters);
            try {
                mCamera.setPreviewDisplay(mHolder);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
            mCamera.startPreview();

        }else{
            if(CAMERA_ID==1){
                CAMERA_ID = 0;
            }else{
                CAMERA_ID = 1;
            }
            startPreview();
        }

    }

    public void stopPreview() {
        //释放Camera对象
        if (mCamera != null) {
            try {
                mCamera.setPreviewDisplay(null);
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    private Camera.Size getBestPreviewSize(int width, int height,
                                           Camera.Parameters parameters) {
        Camera.Size result = null;

        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;

                    if (newArea > resultArea) {
                        result = size;
                    }
                }
            }
        }

        return result;
    }

    @Override
    public void onClick(View v) {
        /*switch (v.getId()) {
            case R.id.start:
                if (!mIsTimerRunning) {
                    mIsTimerRunning = true;
                    mHandler.post(timerRunnable);
                }
                break;
        }*/
    }

    private Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            if (mCurrentTimer > 0) {
                mTvCountDown.setText(mCurrentTimer + "");
                if(mCurrentTimer!=0){
                    mCurrentTimer--;
                }
                mHandler.postDelayed(timerRunnable, 3000);
            } else {
                mTvCountDown.setText("");
                if(mCamera!=null){
                    try{
                        mCamera.takePicture(null, null, null, TakePhotoActivity.this);
                        playSound();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
                mIsTimerRunning = false;
                mCurrentTimer = 3;
            }
        }
    };

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        try {
            if(CAMERA_ID==0&&arrList.size()>=2){
                arrList.remove(0);
            }
            if(CAMERA_ID==1&&arrLists.size()>=2){
                arrLists.remove(0);
            }
            String files =
                    Environment.getExternalStorageDirectory() + File.separator +
                            System.currentTimeMillis() + ".jpg";
            FileOutputStream fos = new FileOutputStream(new File(files));
            if(CAMERA_ID==0){
                arrList.add(files);
            }
            if(CAMERA_ID==1){
                arrLists.add(files);
            }


            //旋转角度，保证保存的图片方向是对的
            /*Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            Matrix matrix = new Matrix();
            matrix.setRotate(90);
           *//* bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);*//*
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            if(arrList.size()>1){
                fos.write(imgarr);
            }
            //ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;//直接设置它的压缩率，表示1/2
            fos.flush();
            fos.close();*/
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            Matrix matrix = new Matrix();
            matrix.setRotate(90);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100 , fos);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;//直接设置它的压缩率，表示1/2
            //String picpress = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
            fos.flush();
            fos.close();
            //byte[] imgarr = FileUtil.imageToBytes(files);

            bitmap = BitmapFactory.decodeFile(files, options);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            if(arrList.size()>1){
                imgarr = bos.toByteArray();
            }
            bos.flush();
            bos.close();
            //String picpress = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
            /*bitmap = BitmapFactory.decodeFile(files, options);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos);
            byte[] imgarr = bos.toByteArray();
            Toast.makeText(TakePhotoActivity.this,"len-->"+imgarr.length,Toast.LENGTH_SHORT).show();
            Log.e("len","lensss-->"+imgarr.length);
            bos.flush();
            bos.close();*/

            //NetUtil.uploadPic(imgarr,TakePhotoActivity.this);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }



        if(mCamera!=null){
            mCamera.startPreview();
        }else{
            try {
                mCamera = Camera.open(CAMERA_ID);
                mCamera.startPreview();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

    }

    /**
     *   播放系统拍照声音
     */
    public void playSound() {
        MediaPlayer mediaPlayer = null;
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int volume = audioManager.getStreamVolume( AudioManager.STREAM_NOTIFICATION);

        if (volume != 0) {
            if (mediaPlayer == null)
                mediaPlayer = MediaPlayer.create(this,
                        Uri.parse("file:///system/media/audio/ui/camera_click.ogg"));
            if (mediaPlayer != null) {
                mediaPlayer.start();
            }
        }
    }

    @Override
    public boolean onNavigationItemSelected(@android.support.annotation.NonNull MenuItem item) {
        Updatefile fileData = DataSupport.findLast(Updatefile.class);

        /*if(fileData==null){
            TextView appversion = (TextView)findViewById(R.id.appversion);
            appversion.setText("当前版本号:"+vcode);
        }else{
            TextView appversion = (TextView)findViewById(R.id.appversion);
            appversion.setText("当前版本号:"+fileData.getVersioncode());
        }*/
        PackageManager packageManager=getApplication().getPackageManager();
        PackageInfo packageInfo;
        int versionCode = 0;
        try {
            packageInfo=packageManager.getPackageInfo(getApplication().getPackageName(),0);
            versionCode=packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        TextView appversion = (TextView)findViewById(R.id.appversion);
        appversion.setText("当前版本号:"+versionCode);

        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            String imei = "";
           /* Context context = getApplicationContext();
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            if (telephonyManager != null) {
                imei = telephonyManager.getDeviceId();
            }*/

            String macAddress = "";
            Context context = MyApplication.instance.getApplicationContext();
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
            if (telephonyManager != null) {
                imei = telephonyManager.getDeviceId();
            }
            if(imei==null || imei.equals("")){
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                if (wifiManager != null) {
                    imei = wifiManager.getConnectionInfo().getMacAddress();
                }
            }
            if(imei==null || imei.equals("")) {
                String androidID = Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
                imei = androidID + Build.SERIAL;
            }
            if(imei==null || imei.equals("")) {
                imei = UUID.randomUUID().toString();
            }

            imei = SerialNumber.getDeviceNo();
            //String updatestr = "14";
            TextView devideid  = (TextView)findViewById(R.id.devideid);
            if(imei!=null){
                if(imei.length()==15){
                    imei = imei+"00";
                    //item.setTitle("设备ID:"+imei);
                    devideid.setText("设备ID:"+imei);
                }else if(imei.length()==16){
                    imei = imei+"0";
                    //item.setTitle("设备ID:"+imei);
                    devideid.setText("设备ID:"+imei);
                }else{
                    //item.setTitle("设备ID:"+imei);
                    devideid.setText("设备ID:"+imei);
                }
            }
            Log.e("序列号",imei);
            Log.e("序列号长度",imei.length()+"");
            Device device = new Device();
            device.setDeviceid(imei);
            device.saveThrows();
        }


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
